// pages/cashCoupon/cashCoupon.js
var app = getApp();
const getShareInfoUrl = '/Fans/getCashShareContent';
const getPageInfoUrl = '/Fans/getCash';
const receiveUrl = '/Fans/openCash';
const getWelfareInfoUrl = '/Fans/cashCoupon';
const getQRCodeImgUrl = '/WelfareQrCode/getQrCode';
const getGoodsListUrl = '/Goods/recommend';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    displayAuthShow: 0,//控制授权弹层的显示和隐藏
    isLoading: 1,//是否显示加载中图标
    goodslist: [],
    page: 1,//商品列表的页码
    QRCodeImg: '',//二维码图片地址
    QRCodeImgHttp:'',//http二维码图片地址
    isUseHttp: 0,//判断是否使用http
    isQRCodeMaskShow: 0,//控制分享二维码弹层的显示
    term:'',//红包使用期限
    quota:'',//红包额度
    invite_code: '',//邀请码
    cash_id:0,//优惠券ID
    uid: 0,//分享者的用户ID
    avatar: '',//用户头像
    user_nick: '',//用户昵称
    is_receive: 0,//是否已经领取过了
    is_vip: 0,//判断当前用户是否是从
    isShareMaskShow: 0,//控制分享的弹层显示
    winWidth: 0, //手机屏幕的宽度
    winHeight: 0, //手机屏幕的高度
    shareTitle: '', //分享标题
    shareImg: '', //分享图片
    sharePath: '' //分享路径
  },
  // 免费领按钮
  freeReceive: function (e) {
    var _this = this;
    var theGoodsId = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + theGoodsId,
    })
  },
  // 阻止点击事件
  preventEvent: function () {
  },
  // 立即使用福利
  useWelfareEvent: function (e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  // 点击发送粉丝福利按钮
  sendWelfare: function (e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    this.setData({
      isShareMaskShow: 1
    })
  },
  // 立即领取现金券
  receiveEvent: function (e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      uid: _this.data.uid,
      cash_id: _this.data.cash_id
    }
    app.post(receiveUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          quota: res.data.price,
          term: res.data.date,
          is_receive: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 关闭分享弹层
  closeMask: function () {
    this.setData({
      isShareMaskShow: 0
    })
  },
  // 关闭分享二维码弹层
  closeQRCodeMask: function () {
    this.setData({
      isQRCodeMaskShow: 0
    })
  },
  // 获取页面信息
  getPageInfo: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      uid: _this.data.uid,
      cash_id: _this.data.cash_id
    }
    app.post(getPageInfoUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          isLoading:0,
          avatar: res.data.image,
          user_nick: res.data.user_nick,
          is_receive: 0
        })
      } else if (res.code == 2004) {
        _this.setData({
          isLoading: 0,
          quota: res.data.price,
          term: res.data.date,
          is_receive: 1
        })
      } else if (res.code == 2005) {
        _this.getWelfareInfo();
        _this.setData({
          isLoading: 0,
          is_vip: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 发送粉丝福利时获取红包信息
  getWelfareInfo:function(){
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      cash_id: _this.data.cash_id
    }
    app.post(getWelfareInfoUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          term: res.data.day,
          quota: res.data.price,
          is_receive: 0
        })
     } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 获取商品推荐列表接口
  getGoodsList: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      search_type: 0,
      page: _this.data.page
    }
    app.post(getGoodsListUrl, requestData, function (res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var goodslist = _this.data.goodslist;
        var configs = wx.getStorageSync('configs');
        console.log(configs.static_url_http);
        for (var i = 0; i < res.data.list.length; i++) {
          res.data.list[i].img = configs.static_url_http + '/' + res.data.list[i].img;
        }
        goodslist = goodslist.concat(res.data.list);
        
        _this.setData({
          page: res.data.page,
          goodslist: goodslist
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    if (options.is_vip) {
      _this.setData({
        is_vip: options.is_vip
      })
    }
    if (options.uid) {
      _this.setData({
        uid: options.uid
      })
    }
    if (options.cash_id) {
      _this.setData({
        cash_id: options.cash_id
      })
    }
    var scene = decodeURIComponent(options.scene);
    if (scene && scene !== 'undefined') {
      var sceneParams = new Array();
      sceneParams = scene.split('#');
      _this.setData({
        uid: sceneParams[0],
        cash_id: sceneParams[1],
      })
    }
    app.checkAuthioze(success => {
      _this.loop();
    }, fail => {
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
// 获取手机型号
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.search('iOS') == -1) {
          _this.setData({
            isUseHttp: 1
          })
        } else {
          _this.setData({
            isUseHttp: 0
          })
        }
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        })
      }
    });
    
  },
  /*角色权限控制*/
  getUserInfo: function (e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function () {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow: 0,
          isfriendShareMaskShow: 1,
          cash: cash
        })
      }
      that.loop();
      wx.navigateBack({
        delta: 1,
      })
    });
  },
  authRest: function () {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function () {
      wx.reLaunch({
        url: '/pages/bargain/bargain',
      })
    }, 1000)
  },
  // 判断是否获取到token的值了
  loop: function () {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function () { _this.loop() }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getPageInfo();
      _this.getShareInfo();
      _this.getGoodsList();
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 获取二维码图片
  getQRCodeImg: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      share_type: 1,
      cash_id: _this.data.cash_id
    }
    app.post(getQRCodeImgUrl, requestData, function (res) {
      if(res.code==2000){
      _this.setData({
        QRCodeImg: res.data.image,
        QRCodeImgHttp: res.data.image_http
      })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  // 点击获取生成二维码按钮
  gerQrcode: function (e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.getQRCodeImg();
    _this.setData({
      isQRCodeMaskShow: 1,
      isShareMaskShow: 0
    })
  },
  // 保存图片
  saveImg: function (e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    console.log(e);
    wx.downloadFile({
      url: _this.data.QRCodeImg,
      success: function (res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            console.log(res)
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (res) {
            console.log(res)
            console.log('fail')
          }
        })
      },
      fail: function () {
        console.log('fail')
      }
    })
  },
  // 预览图片
  previewImg: function () {
    var _this = this;
    var urls;
    if (_this.data.isUseHttp==1){
      urls = [_this.data.QRCodeImgHttp]
    }else{
      urls = [_this.data.QRCodeImg]
    }
    wx.previewImage({
      current: _this.data.QRCodeImg, // 当前显示图片的http链接
      urls: urls
    })
  },
  // 获取分享信息
  getShareInfo: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      cash_id: _this.data.cash_id
    }
    app.post(getShareInfoUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          shareTitle: res.data.title,
          shareImg: res.data.img,
          sharePath: res.data.page
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this = this;
    return {
      title: _this.data.shareTitle,
      path: _this.data.sharePath,
      imageUrl: _this.data.shareImg
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getGoodsList();
  },
  // 获取当前时间并且转化格式
  getNowFormatDate: function (date) {
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    if(month >= 1 && month <= 9) {
  month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
  strDate = "0" + strDate;
}
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + ':' + minutes + ':' + seconds;
return currentdate;
    }
})